import dayjs from 'dayjs';
export const isStr = (val: any): val is Function => typeof val === 'string'
export const isFunc = (val: any): val is Function => typeof val === 'function'
export const isObject = (val: any) => Object.prototype.toString.call(val) == '[object Object]';
export const isArray = (val: any) => Array.isArray(val);

export const msg = {
    info: (text: string) => ElMessage(text),
    success: (text: string) => ElMessage.success(text),
    warning: (text: string) => ElMessage.warning(text),
    error: (text: string) => ElMessage.error(text),
}

// 待考虑
// const findItemSet = (items: any[], keyName: string, itemKey: string, itemValue: any) => {
//     items.map((item: any) => {
//         if (item.key === keyName) {
//             item[itemKey] = itemValue;
//         }
//     })
// }

const u = {
    // findItemSet
}

// 事件中心
export const eventCenter = (params: any, action: any) => {
    const { item, eventName } = params
	if (eventName === 'click' && item.actionName && action[item.actionName]) {
        action[item.actionName]({...params, msg})
	} else {
		if (item.on && item.on[eventName]) {
			item.on[eventName]({...params, msg, u})
		}
	}
}

// 表格内置格式化方法
export const tableFormat: any = {
    // 用* 加密显示数字和字符串
    star: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return row[item.key].toString().replace(/./g, '*')
    },
    // 百分比
    percentage: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return `${row[item.key]}%`
    },
    // 小时
    h: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return `${row[item.key]}h`
    },
    // 人民币
    rmb: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return `￥${row[item.key] ? parseFloat(row[item.key]).toFixed(2) : ''}`
    },
    // 美元
    $: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return `$${row[item.key] ? parseFloat(row[item.key]).toFixed(2) : ''}`
    },
    // 时间戳转换为日期
    date: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return row[item.key].toString() && row[item.key].toString().length < 13
            ? dayjs.unix(row[item.key]).format('YYYY-MM-DD')
            : dayjs(row[item.key]).format('YYYY-MM-DD')
    },
    // 时间戳转换为日期时间
    datetime: ({ row, item }: any) => {
        if (!row[item.key]) return '';
        return row[item.key].toString() && row[item.key].toString().length < 13
            ? dayjs.unix(row[item.key]).format('YYYY-MM-DD HH:mm:ss')
            : dayjs(row[item.key]).format('YYYY-MM-DD HH:mm:ss')
    },
    // 搭配 ui: select 使用
    select: ({ row, item, initData, multiple }: any) => {
        if (!(item.dict && item.dict.data)) return ''
        let data: any[] = isFunc(item.dict.data)
            ? item.dict.data({ row, item, initData })
            : item.dict.data
        if (!Array.isArray(data)) return ''
        if (multiple) {
            if (!row[item.key]) return ''
            return data.filter((_item: any) => row[item.key].includes(_item['value'])).map((_item: any) => _item['label']).join(', ')
        } else {
            const cur = data.find((_item: any) => _item['value'] === row[item.key])
            return cur ? cur['label'] : ''
        }
    }
}

type TableFormat = typeof tableFormat
export type TableFormatKey = keyof TableFormat

// 设置初始化数据
interface InitData {
    [key: string] : any
}
export const setInitData = (propsInitData: InitData, stateInitData: InitData, form = {}, serialization = false, showLog = false) => {
    return new Promise<void>(async(resolve, reject) => {
        for (const key in propsInitData) {
            if (showLog) log( `执行 initData 开始`, `key: ${key}`)
            
            if (isFunc(propsInitData[key])) {
                const params = { form, initData: stateInitData }
                if (serialization) { // 利用async await 的特性，实现序列化请求
                    const { data } = await propsInitData[key](params)
                    if (!data) return log( `异步请求${key}:`, `接口响应缺少 data 字段`, 'warn')
                    stateInitData[key] = data
                } else {
                    propsInitData[key](params)
                        .then(({ data }: any) => {
                            if (!data) return log( `异步请求${key}:`, `接口响应缺少 data 字段`, 'warn')
                            stateInitData[key] = data
                        })
                }
            } else {
                stateInitData[key] = propsInitData[key]
            }
        }
        if (showLog) log( `执行 initData 结束`, stateInitData)
        resolve()
    })
}

// 日志打印
export const log = (key: string, value: any, type?: string) => {
    if (type === 'warn') return console.warn(`log: ${key}`, value)
    console.log(`log: ${key}`, value);
}